/**
 * Created by Jone on 2016/7/15.
 */

App.config(['$stateProvider', '$locationProvider', '$urlRouterProvider', 'RouteHelpersProvider',
    function ($stateProvider, $locationProvider, $urlRouterProvider, helper) {
        $stateProvider
            .state('app-api.interface_list_view', {
                url: '/interface/list/view',
                controller: 'InterfaceController',
                templateUrl: helper.basepath('interface/view.html'),
                resolve: helper.resolveFor( 'toaster', 'whirl', 'ng-nestable')
            })
            .state('app-api.interface_list_all', {
                url: '/interface/list/all',
                controller: 'InterfaceController',
                templateUrl: helper.basepath('interface/list.html'),
                resolve: helper.resolveFor( 'toaster', 'whirl', 'ng-nestable')
            })
            .state('app-api.interface_create', {
                url: '/interface/create',
                title: 'Single View',
                controller: 'InterfaceController',
                templateUrl: helper.basepath('interface/create.html'),
                resolve: helper.resolveFor( 'toaster', 'whirl', 'ng-nestable', 'xeditable')
            })
            .state('app-api.interface_update', {
                url: '/interface/update',
                title: 'Single View',
                controller: 'InterfaceController',
                params : {interface : null},
                templateUrl: helper.basepath('interface/update.html'),
                resolve: helper.resolveFor( 'toaster', 'whirl', 'ng-nestable')
            })
            .state('app-api.interface_detail', {
                url: '/interface/detail',
                title: 'Single View',
                controller: 'InterfaceController',
                params : {interface : null},
                templateUrl: helper.basepath('interface/detail.html'),
                resolve: helper.resolveFor( 'toaster', 'whirl', 'ng-nestable')
            })

    }]);


App.controller('InterfaceController', function ($scope, $http, $cookieStore, $location, $window, $state, $stateParams, toaster,  $filter, $q ) {

    $scope.users = [
        {id: 1, name: 'param', status: 2, desc: 4},
        {id: 2, name: 'param', status: undefined, desc: 3},
        {id: 3, name: 'param', status: 2, desc: null}
    ];

    $scope.statuses = [
        {value: 1, text: 'string'},
        {value: 2, text: 'number'},
        {value: 3, text: 'object'},
        {value: 4, text: 'array'}
    ];

    $scope.showStatus = function(user) {
        var selected = [];
        if(user.status) {
            selected = $filter('filter')($scope.statuses, {value: user.status});
        }
        return selected.length ? selected[0].text : 'Not set';
    };

    $scope.checkName = function(data, id) {
        if (id === 2 && data !== 'awesome') {
            return "Username 2 should be `awesome`";
        }
    };

    $scope.saveUser = function(data, id) {
        //$scope.user not updated yet
        angular.extend(data, {id: id});
        console.log('Saving user: ' + id);
        // return $http.post('/saveUser', data);
    };

    // remove user
    $scope.removeUser = function(index) {
        $scope.users.splice(index, 1);
    };

    // add user
    $scope.addUser = function() {
        $scope.inserted = {
            id: $scope.users.length+1,
            name: '',
            status: null,
            isNew: true
        };
        $scope.users.push($scope.inserted);
    };

    // editable column
    // -----------------------------------


    $scope.saveColumn = function(column) {
        var results = [];
        angular.forEach($scope.users, function(user) {
            // results.push($http.post('/saveColumn', {column: column, value: user[column], id: user.id}));
            console.log('Saving column: ' + column);
        });
        return $q.all(results);
    };

    // editable table
    // -----------------------------------

    // filter users to show
    $scope.filterUser = function(user) {
        return user.isDeleted !== true;
    };

    // mark user as deleted
    $scope.deleteUser = function(id) {
        var filtered = $filter('filter')($scope.users, {id: id});
        if (filtered.length) {
            filtered[0].isDeleted = true;
        }
    };

    // cancel all changes
    $scope.cancel = function() {
        for (var i = $scope.users.length; i--;) {
            var user = $scope.users[i];
            // undelete
            if (user.isDeleted) {
                delete user.isDeleted;
            }
            // remove new
            if (user.isNew) {
                $scope.users.splice(i, 1);
            }
        }
    };

    // save edits
    $scope.saveTable = function() {
        var results = [];
        for (var i = $scope.users.length; i--;) {
            var user = $scope.users[i];
            // actually delete user
            if (user.isDeleted) {
                $scope.users.splice(i, 1);
            }
            // mark as not new
            if (user.isNew) {
                user.isNew = false;
            }

            // send on server
            // results.push($http.post('/saveUser', user));
            console.log('Saving Table...');
        }

        return $q.all(results);
    };















    $scope.getGroups = function() {
        $http.get("/groups", {params : {projectId : $cookieStore.get("project")._id}})
            .success(function (response) {
                $scope.groups = response.data;
            })
            .error(function(data) {

            });
    }


    $scope.submitted = false;
    $scope.validateInput = function(name, type) {
        var input = $scope.formValidate[name];
        return (input.$dirty || $scope.submitted) && input.$error[type];
    };

    $scope.create = function() {
        $scope.submitted = true;
        if ($scope.formValidate.$valid) {
            $http.post("/interfaces", $scope.interface)
                .success(function (response) {
                    if (response.code == 0) {
                        toaster.pop('success', '提示', '创建成功');
                    }
                });
            console.log('Submitted!!');
        } else {
            console.log('Not valid!!');
            return false;
        }
    }

    $scope.update = function() {
        $scope.submitted = true;
        if ($scope.formValidate.$valid) {
            try{
                var request = JSON.parse($scope.interface.request);
                var response = JSON.parse($scope.interface.response);
            }catch(e) {
                toaster.pop('error', '提示', " json格式不正确");
                return;
            }
            $scope.interface.response = JSON.stringify(response, null, '\t');
            $scope.interface.request = JSON.stringify(request, null, '\t');
            $http.put("/interfaces", $scope.interface)
                .success(function (response) {
                    if (response.code == 0) {
                        $scope.interface = response.data;
                        toaster.pop('success', '提示', '修改成功');
                    }
                });
        } else {
            console.log('Not valid!!');
            return false;
        }
    }

    $scope.delete = function(interface) {
        $http.delete("/interfaces/" + interface._id)
            .success(function (response) {
                if (response.code == 0) {
                    alert("success");
                    $http.get("/interfaces")
                        .success(function (response) {
                            $scope.interfaces = response.data;
                        })
                        .error(function(data) {

                        });
                }
            });
    }

    $scope.select = function() {
        $state.go('app-api.interface_create', {project: $scope.project});
    }

    $scope.list = function() {
        $http.get("/groups/interfaces", {params : {projectId : $cookieStore.get("project")._id}})
            .success(function (response) {
                $scope.groups = response.data;
            })
            .error(function(data) {

            });
    }

    $scope.interface = $stateParams.interface;
});